package com.quick.threadtest;

import java.util.concurrent.CountDownLatch;

public class CountDownLatchTest {
    public static void main(String[] args) throws Exception{
        CountDownLatch countDownLatch = new CountDownLatch(6);
        for (int i = 0; i < 5; i++) {
            Thread thread = new Thread(new FirstBatchWorker(countDownLatch));
            thread.start();
        }
        for (int i = 0; i < 5; i++) {
            Thread thread = new Thread(new SecondBatchWorker(countDownLatch));
            thread.start();
        }
        while (countDownLatch.getCount()!=1){
            Thread.sleep(100l);
        }
        System.out.println("wait for first is finish!!");
        countDownLatch.countDown();
    }
}
class FirstBatchWorker implements Runnable{
    private CountDownLatch countDownLatch;
    public FirstBatchWorker(CountDownLatch countDownLatch){
        this.countDownLatch = countDownLatch;
    }
    @Override
    public void run() {
        System.out.println("first batch executed!!");
        countDownLatch.countDown();
    }
}
class SecondBatchWorker implements Runnable{
    private CountDownLatch countDownLatch;
    public SecondBatchWorker(CountDownLatch countDownLatch){
        this.countDownLatch = countDownLatch;
    }
    @Override
    public void run() {
        try {
            countDownLatch.await();
            System.out.println("second batch executed!!");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}